package local.blueheart.data.springdatademo.task;

import local.blueheart.data.springdatademo.annotation.TaskWorker;
import local.blueheart.data.springdatademo.domain.archive.ArchivedServerDBData;
import local.blueheart.data.springdatademo.repository.archive.ArchiveIndexRepository;
import local.blueheart.data.springdatademo.service.ArchiveDataService;
import local.blueheart.data.springdatademo.service.impl.ArchiveDataServiceImpl;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.List;
import java.util.concurrent.Executor;

@TaskWorker("数据归档任务")
public class DataArchivedTask implements Job, ApplicationContextAware {

    private static final Logger LOGGER = LoggerFactory.getLogger(DataArchivedTask.class);

    private ApplicationContext applicationContext;


    @Autowired
    private ArchiveIndexRepository archiveIndexRepository;

    @Autowired
    private Executor executor;

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        List<ArchivedServerDBData> allDataDbList = archiveIndexRepository.findAllDataDbList();
        for(ArchivedServerDBData archivedServerDBData:allDataDbList) {
            ArchiveDataService archiveDataService = (ArchiveDataService) applicationContext.getBean("archiveDataService");
            ((ArchiveDataServiceImpl) archiveDataService).setArchivedServerDBData(archivedServerDBData);
            executor.execute(archiveDataService);
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
